import Crud from '@/components/Crud';
import { LoadPlaceSelect, UnloadPlaceSelect } from '@/components/CustomForm';
import {
  CHECK_TYPE_MAP,
  LEVEL_MAP,
  LINE_TYPE_OPTIONS,
  STATE_OPTIONS,
} from '@/constants/enums';
import useMaterial from '@/hooks/useMaterial';
import request from '@/utils/request';
import { DeleteOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Input, Modal, Select, Space, message } from 'antd';
import { useRef, useState } from 'react';
import Detail from './components/Detail';
import Save from './components/Save';

const getList = async (params) => {
  const res = await request({
    url: '/datas/line/list',
    method: 'GET',
    custom: true,
    params: params,
  });
  return {
    total: res?.total,
    data: res?.data,
  };
};

const Index = () => {
  const [mode, setMode] = useState('list');
  const [record, setRecord] = useState();
  const [selectedKeys, setSelectedKeys] = useState([]);
  const crudRef = useRef();
  const { materialTypeMap } = useMaterial();
  const deleteRow = (id) => {
    const ids = id ? [id] : selectedKeys;
    Modal.confirm({
      title: `确认删除所选数据?`,
      onOk: async () => {
        await request({
          url: '/datas/line/delete',
          method: 'POST',
          data: { ids },
        });
        message.success('操作成功');
        crudRef.current?.reload();
        setSelectedKeys([]);
      },
    });
  };

  const columns = [
    {
      title: '序号',
      fixed: 'left',
      width: 65,
      render: (text, record, index) => index + 1,
    },
    {
      title: '线路名称',
      dataIndex: 'lineName',
      fixed: 'left',
      width: 280,
    },
    {
      title: '全称',
      dataIndex: 'fullName',
      width: 380,
    },
    {
      title: '装货地',
      dataIndex: 'loadPlaceName',
      width: 150,
    },
    {
      title: '卸货地',
      dataIndex: 'unloadPlaceName',
      width: 150,
    },
    {
      title: '其他卸货地',
      dataIndex: 'unloadPlaceName2',
      width: 150,
    },
    {
      title: '线路编号',
      dataIndex: 'lineCode',
      width: 120,
    },
    {
      title: '线路类型',
      dataIndex: 'lineType',
      width: 120,
      render: (text) =>
        LINE_TYPE_OPTIONS.find((item) => item.value === text)?.label,
    },
    {
      title: '物料类型',
      dataIndex: 'type',
      width: 120,
      render: (text) => materialTypeMap[text],
    },
    {
      title: '空载里程',
      dataIndex: 'emptyMileages',
      width: 120,
    },
    {
      title: '重载里程',
      dataIndex: 'heavyMileages',
      width: 120,
    },
    {
      title: '空载时长',
      dataIndex: 'emptyTimes',
      width: 120,
      render: (text) => `${text}分钟`,
    },
    {
      title: '重载时长',
      dataIndex: 'heavyTimes',
      width: 120,
      render: (text) => `${text}分钟`,
    },
    {
      title: '报计划站点',
      dataIndex: 'planStationName',
      width: 150,
    },
    {
      title: '单价(元/吨)',
      dataIndex: 'price',
      width: 120,
    },
    {
      title: '司机单价(元/趟)',
      dataIndex: 'driverPrice',
      width: 140,
    },
    {
      title: '状态',
      dataIndex: 'state',
      width: 100,
      render: (text) =>
        STATE_OPTIONS.find((item) => item.value === text)?.label,
    },
    {
      title: '级别',
      dataIndex: 'level',
      width: 100,
      render: (text) => LEVEL_MAP[text],
    },
    {
      title: '核算类型',
      dataIndex: 'checkType',
      width: 100,
      render: (text) => CHECK_TYPE_MAP[text],
    },
    {
      title: '核算系数',
      dataIndex: 'checkRatio',
      width: 100,
    },
    {
      title: '装车费',
      dataIndex: 'loadPrice',
      width: 100,
      render: (text) => `¥${text}`,
    },
    {
      title: '卸车费',
      dataIndex: 'unloadPrice',
      width: 100,
      render: (text) => `¥${text}`,
    },
    {
      title: '信息费',
      dataIndex: 'infoPrice',
      width: 100,
      render: (text) => `¥${text}`,
    },
    {
      title: '篷布费',
      dataIndex: 'tarpaulinPrice',
      width: 100,
      render: (text) => `¥${text}`,
    },
    {
      title: '过磅费',
      dataIndex: 'passWeightPrice',
      width: 100,
      render: (text) => `¥${text}`,
    },
    {
      title: '上车台费',
      dataIndex: 'upCarPrice',
      width: 100,
      render: (text) => `¥${text}`,
    },
    {
      title: '下车台费',
      dataIndex: 'downCarPrice',
      width: 100,
      render: (text) => `¥${text}`,
    },
    {
      title: '折损系数',
      dataIndex: 'lossRatio',
      width: 100,
    },
    {
      title: '磅单差价',
      dataIndex: 'discrepancyPrice',
      width: 100,
      render: (text) => `¥${text || 0}`,
    },
    {
      title: '其他费用',
      dataIndex: 'otherPrice',
      width: 100,
      render: (text) => `¥${text || 0}`,
    },
    {
      title: '客户单位',
      dataIndex: 'customerName',
      width: 200,
    },
    {
      title: '系统时间',
      dataIndex: 'time',
      width: 180,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      width: 140,
    },
    {
      title: '操作',
      fixed: 'right',
      dataIndex: 'operate',
      width: 160,
      render: (text, record) => {
        return (
          <Space>
            <a
              className="btn-operate"
              onClick={() => {
                setRecord(record);
                setMode('detail');
              }}
            >
              详情
            </a>
            <a
              className="btn-operate"
              onClick={() => {
                setRecord(record);
                setMode('edit');
              }}
            >
              编辑
            </a>
            <a
              onClick={() => {
                deleteRow(record.lineId);
              }}
            >
              删除
            </a>
          </Space>
        );
      },
    },
  ];

  const fields = [
    {
      label: '装货地',
      name: 'loadPlaceId',
      children: <LoadPlaceSelect />,
    },
    {
      label: '卸货地',
      name: 'unloadPlaceId',
      children: <UnloadPlaceSelect />,
    },
    {
      label: '线路名称',
      name: 'lineName',
      children: <Input placeholder="请输入线路名称" />,
    },
    {
      label: '状态',
      name: 'state',
      children: (
        <Select
          allowClear
          placeholder="请选择"
          options={[
            { label: '启用', value: 0 },
            { label: '弃用', value: 1 },
          ]}
        />
      ),
    },
  ];

  return (
    <>
      <Crud
        ref={crudRef}
        rowKey="lineId"
        queryFormProps={{ labelCol: 7 }}
        fields={fields}
        columns={columns}
        request={getList}
        toolbar={
          <>
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setMode('create')}
            >
              新增
            </Button>
            <Button
              icon={<DeleteOutlined />}
              disabled={selectedKeys.length === 0}
              onClick={() => deleteRow()}
            >
              批量删除
            </Button>
          </>
        }
        tableProps={{
          rowSelection: {
            selectedRowKeys: selectedKeys,
            onChange: (selectedRowKeys) => {
              setSelectedKeys(selectedRowKeys);
            },
          },
        }}
      />
      <Save
        open={mode === 'create' || mode === 'edit'}
        record={record}
        onCancel={() => {
          setMode('list');
          setRecord(null);
          crudRef.current?.reload();
        }}
      />
      <Detail
        open={mode === 'detail'}
        record={record}
        onCancel={() => {
          setMode('list');
          setRecord(null);
        }}
      />
    </>
  );
};

export default Index;
